<template>
  <div class="customer-page">
    <van-nav-bar
      title="客户管理"
      left-arrow
      @click-left="router.back()"
    />

    <!-- 搜索栏 -->
    <div class="search-bar">
      <van-search
        v-model="searchKeyword"
        placeholder="搜索客户姓名"
        @search="handleSearch"
      />
    </div>

    <!-- 客户列表 -->
    <div class="customer-list" ref="customerListRef" @scroll="onScroll">
      <van-empty v-if="customerList.length === 0 && !loading" description="暂无客户数据" />
      
      <van-cell-group v-if="customerList.length > 0">
        <div 
          v-for="customer in customerList" 
          :key="customer.id"
          class="customer-item"
        >
          <van-cell center :border="false" @click="handleEdit(customer)">
            <template #icon>
              <div class="avatar-container">
                <img :src="customer.image" class="avatar" />
              </div>
            </template>
            <template #title>
              <div class="customer-name">{{ customer.buyerName }}</div>
            </template>
            <template #label>
              <div class="customer-info">
                <span class="phone">{{ formatPhone(customer.contact) }}</span>
              </div>
            </template>
            <template #right-icon>
              <div class="action-buttons">
                <van-button
                  size="small"
                  type="primary"
                  class="edit-button"
                  @click.stop="handleEdit(customer)"
                >
                  编辑
                </van-button>
                <van-button
                  size="small"
                  type="danger"
                  class="delete-button"
                  @click.stop="handleDelete(customer)"
                >
                  删除
                </van-button>
              </div>
            </template>
          </van-cell>
        </div>
      </van-cell-group>
      
      <!-- 加载状态显示 -->
      <div class="loading-status" v-if="customerList.length > 0 || loading">
        <van-loading v-if="loading" type="spinner" size="24px" />
        <span v-else-if="!hasMore">没有更多数据了</span>
        <span v-else>上拉加载更多</span>
      </div>
    </div>

    <!-- 添加客户按钮 -->
    <div class="add-customer-button">
      <van-button 
        round 
        type="primary" 
        icon="plus" 
        @click="handleAdd"
      >
        添加新客户
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showDialog } from 'vant'
import { getCustomerList, deleteCustomer, type Customer, type PageResult } from '../api/customer'

const router = useRouter()
const searchKeyword = ref('')
const customerList = ref<Customer[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const hasMore = ref(true)
const customerListRef = ref<HTMLElement | null>(null)

// 获取客户列表
const fetchCustomerList = async (isLoadMore = false) => {
  if (loading.value || (!isLoadMore && !hasMore.value)) return

  loading.value = true
  try {
    const pageData: PageResult<Customer> = await getCustomerList(
      searchKeyword.value,
      currentPage.value,
      pageSize.value
    )
    
    if (isLoadMore) {
      // 加载更多模式，将新数据追加到列表末尾
      customerList.value = [...customerList.value, ...pageData.records]
    } else {
      // 初始加载或搜索模式，替换整个列表
      customerList.value = pageData.records
    }
    
    total.value = pageData.total
    
    // 判断是否还有更多数据
    hasMore.value = customerList.value.length < total.value
  } catch (error) {
    console.error('获取客户列表失败:', error)
    if (!isLoadMore) {
      customerList.value = []
      total.value = 0
    }
  } finally {
    loading.value = false
  }
}

// 搜索客户
const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置为第一页
  hasMore.value = true  // 重置加载更多状态
  fetchCustomerList()
}

// 加载下一页
const loadMore = () => {
  if (loading.value || !hasMore.value) return
  
  currentPage.value += 1
  fetchCustomerList(true)
}

// 滚动事件处理
const onScroll = (event: Event) => {
  if (!customerListRef.value) return
  
  const { scrollTop, clientHeight, scrollHeight } = customerListRef.value
  // 当滚动到距离底部50px以内时，加载更多数据
  if (scrollHeight - scrollTop - clientHeight < 50 && !loading.value && hasMore.value) {
    loadMore()
  }
}

// 添加客户
const handleAdd = () => {
  router.push('/customer/add')
}

// 编辑客户
const handleEdit = (customer: Customer) => {
  router.push(`/customer/edit/${customer.id}`)
}

// 删除客户
const handleDelete = (customer: Customer) => {
  showDialog({
    title: '确认删除',
    message: `确定要删除客户 ${customer.buyerName} 吗？`,
    showCancelButton: true
  }).then(async () => {
    try {
      // 先设置加载状态，避免用户继续操作
      loading.value = true
      
      // 执行删除操作
      await deleteCustomer(customer.id)
      
      // 重置分页参数
      currentPage.value = 1
      hasMore.value = true
      
      // 平滑过渡：不清空现有数据，而是在获取新数据后再替换
      const pageData: PageResult<Customer> = await getCustomerList(
        searchKeyword.value,
        currentPage.value,
        pageSize.value
      )
      
      // 数据准备好后才更新列表
      customerList.value = pageData.records
      total.value = pageData.total
      hasMore.value = customerList.value.length < total.value
      
      // 操作完成后重置加载状态
      loading.value = false
      
      // 如果滚动容器存在，平滑滚动到顶部
      if (customerListRef.value) {
        customerListRef.value.scrollTo({
          top: 0,
          behavior: 'smooth'
        })
      }
    } catch (error) {
      console.error('删除客户失败:', error)
      loading.value = false
    }
  })
}

// 格式化联系方式
const formatPhone = (contact: string) => {
  if (!contact) return '未设置联系方式';
  // 判断是否为手机号格式
  if (/^1\d{10}$/.test(contact)) {
    return contact.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3')
  }
  return contact;
}

onMounted(() => {
  fetchCustomerList()
})
</script>

<style lang="scss" scoped>
.customer-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
  overflow-y: auto;

  .search-bar {
    padding: 8px 0;
    position: sticky;
    top: 0;
    z-index: 100;
  }

  .customer-list {
    flex: 1;
    padding: 0 12px;
    padding-bottom: 80px; /* 为底部按钮预留空间 */
    overflow-y: auto;    /* 添加滚动 */
    -webkit-overflow-scrolling: touch; /* 提高iOS滚动体验 */
    
    .customer-item {
      margin-bottom: 8px;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      
      .avatar-container {
        margin-right: 12px;
        
        .avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          object-fit: cover;
        }
      }
      
      .customer-name {
        font-size: 16px;
        font-weight: 500;
      }
      
      .customer-info {
        display: flex;
        flex-direction: column;
        font-size: 12px;
        color: #999;
        
        .phone {
          margin-bottom: 4px;
        }
      }
      
      .action-buttons {
        display: flex;
        gap: 8px;
        
        .van-button {
          min-width: 54px;
          height: 32px;
          font-size: 12px;
          padding: 0 8px;
          border-radius: 4px;
        }
      }
    }
  }
  
  .loading-status {
    text-align: center;
    padding: 16px 0;
    color: #969799;
    font-size: 14px;
  }

  .add-customer-button {
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 10;
    
    .van-button {
      padding: 0 24px;
      height: 44px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
    }
  }
}
</style> 